package cn.tedu.egweibo0416.base.exception;

import cn.tedu.egweibo0416.base.response.JsonResult;
import cn.tedu.egweibo0416.base.response.StatusCode;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import javax.validation.ConstraintViolationException;

@Slf4j
@RestControllerAdvice     //等于 RestController + ExceptionHandler

public class GlobalExceptionHandle {
    @ExceptionHandler
    public JsonResult doHandleMethodArgumentNotValidException(MethodArgumentNotValidException ex){
        String data = ex.getFieldError().getDefaultMessage();
        log.error("doHandle"+data);
        return new JsonResult(StatusCode.VALIDATED_ERROR,data);
    }
    @ExceptionHandler
    public JsonResult doHandleConstraintViolationException(ConstraintViolationException ex){

//        List<String> errors = ex.getConstraintViolations().stream()
//                .map(violation -> violation.getMessage())
//                .collect(Collectors.toList());
//        String data = String.join(", ", errors);
//        log.error("doHandleConstraintViolationException: {}", data);
//        return new JsonResult(StatusCode.VALIDATION_ERROR, data);
        String data = ex.getMessage().split(":")[1].trim();
        System.out.println(data);
        log.error("doHandleConstraintViolationException"+data);

        return new JsonResult(StatusCode.VALIDATED_ERROR,data);
    }
    @ExceptionHandler
//    @ResponseBody
    public JsonResult doHandlerIllegalArgumentException(IllegalArgumentException ex){
        String data = ex.getMessage();
        log.error("doHandlerIllegalArgumentException"+data);
        return new JsonResult(StatusCode.OPERATION_FAILED,data);
    }

}
